from django.http import HttpResponse
from django.shortcuts import render

from user.models import User


# Create your views here.
def index(request):
    return render(request, 'user/index.html')
def reg_view(request):
    if request.method == 'GET':
        return render(request, 'user/register.html')
    elif request.method == 'POST':
        data = request.POST
        username = data.get('username')
        password = data.get('password')
        password_2 = data.get('password_2')

        if not username or not password:
            return HttpResponse('用户名或密码不能为空!')
        elif User.objects.filter(username=username):
            return HttpResponse('用户名已存在!')
        elif password_2 != password:
            return HttpResponse('两次密码不一致!')

        user = User.objects.create(username=username, password=password)
        return HttpResponse(f'{user.username}创建成功!')


def login_view(request):
    if request.method == 'GET':
        if 'uname' in request.session and 'uid' in request.session:
            return HttpResponse(f'欢迎{request.session["uname"]},请访问其他功能或者'
                                f'<a href="/user/logout">退出登录</a>')
        return render(request, 'user/login.html')
    elif request.method == 'POST':
        data = request.POST
        username = data.get('username')
        password = data.get('password')

        if not username or not password:
            return HttpResponse('用户名或密码为空!')
        try:
            user = User.objects.get(username=username)
        except:
            return HttpResponse('用户名不存在!')
        if password != user.password:
            return HttpResponse('密码错误!')
        # 保持登录状态
        request.session['uname']=user.username
        request.session['uid']=user.id

        return HttpResponse(f"{username}登录成功!<a href='/note/'>跳转到笔记</a>")
        # return render(request,'note/list_note.html',locals())
def logout_view(request):
    if 'uid' not in request.session or 'uname' not in request.session:
        return HttpResponse('未登录!')
    del request.session['uid']
    del request.session['uname']

    return HttpResponse('退出登录成功')


